<template>
    <view>
        <!-- pages/doorList/doorList.wxml -->

        <view class="logo-top" :style="'padding-top:' + (statusBarHeight + 10) + 'px'">
            <view class="logo-name">
                <view class="back iconfont icon-back" @tap="goBack"></view>
                <image class="logo" src="/static/logo.png"></image>
                <text class="name">{{ doorinfodata.storeName }}</text>
            </view>
        </view>
        <view class="container" :style="'padding-top:' + (statusBarHeight + 126) + 'rpx'">
            <image class="topNotice" mode="widthFix" style="width: 100%" src="/static/pages/static/img/notice.png"></image>
            <view class="top-waring-container">
                <view class="top-waring">
                    <image class="img" src="/static/pages/static/icon/caution.png" mode="widthFix" />
                    <rich-text class="info">下单5分钟内可以取消订单，开始订单前可更换场地。迟到消费，订单按原预定时间开始计费。</rich-text>
                </view>
            </view>
            <view class="top-tabs-container">
                <view class="top-tabs">
                    <view data-index="0" :class="'tab ' + (tabIndex === 0 && 'active')" @tap="tabChange">棋牌</view>
                    <view data-index="1" :class="'tab ' + (tabIndex === 1 && 'active')" @tap="tabChange">台球</view>
                    <!-- <view data-index="2" class="tab {{tabIndex === 2 && 'active'}}" bind:tap="tabChange">自习室</view> -->
                </view>
            </view>
            <!-- 房间列表 -->
            <view class="lists" id="roomList" v-for="(item, index) in doorlistArr" :key="index">
                <view class="item">
                    <view class="top">
                        <view class="left">
                            <block v-if="item.imageUrls.length > 0">
                                <image class="img" :src="magic.split(item.imageUrls)[0]" @tap.stop.prevent="imgYu" :data-index="index"></image>
                            </block>
                            <block v-else>
                                <image class="img" src="/static/logo.png"></image>
                            </block>
                            <block v-if="item.status == 0">
                                <view class="flag disabled">禁用</view>
                            </block>
                            <block v-else-if="item.status == 1">
                                <view class="flag undo">空闲中</view>
                            </block>
                            <block v-else-if="item.status == 2">
                                <view class="flag daiqingjie">待清洁</view>
                            </block>
                            <block v-else-if="item.status == 3">
                                <view class="flag doing">使用中</view>
                            </block>
                            <block v-else>
                                <view class="flag bukeyong">已预约</view>
                            </block>
                        </view>
                        <view class="right" @tap.stop.prevent="goOrder" :data-status="item.status" :data-index="index" :data-info="item.roomId">
                            <view class="info">
                                <view class="name">
                                    {{ item.roomName }}
                                    <block v-if="item.type == 0">
                                        <text class="type">（特价包）</text>
                                    </block>
                                    <block v-else-if="item.type == 1">
                                        <text class="type">（小包）</text>
                                    </block>
                                    <block v-else-if="item.type == 2">
                                        <text class="type">（中包）</text>
                                    </block>
                                    <block v-else-if="item.type == 3">
                                        <text class="type">（大包）</text>
                                    </block>
                                    <block v-else-if="item.type == 4">
                                        <text class="type">（豪包）</text>
                                    </block>
                                    <block v-else>
                                        <text class="type">（商务包）</text>
                                    </block>
                                </view>
                                <view class="tags">
                                    <block v-for="(labelitem, index1) in magic.split(item.label)" :key="index1">
                                        <view class="tag">{{ labelitem }}</view>
                                    </block>
                                </view>
                            </view>
                            <view class="line2">
                                <view class="priceLabel">
                                    <view class="price">
                                        每小时
                                        <label class="color-attention">￥{{ item.price }}元</label>
                                    </view>
                                    <!-- <block wx:if="{{item.price!=item.workPrice}}">
                <view class="price">
                  闲时价
                  <label class="color-attention">￥{{item.workPrice}}元</label>
                </view>
              </block>
              <block wx:if="{{doorinfodata.showTxPrice}}">
                <view class="price">
                  通宵场
                  <label class="color-attention">￥{{item.tongxiaoPrice}}元</label>
                </view>
              </block> -->
                                </view>
                                <view class="bottom">
                                    <block v-if="item.status == 0">
                                        <!-- 禁用状态 -->
                                        <view class="btn disabled">禁用</view>
                                    </block>
                                    <block v-else-if="">
                                        <block v-if="isLogin">
                                            <view class="btn bg-primary">预约</view>
                                        </block>
                                        <block v-else>
                                            <button
                                                hover-class="button-click"
                                                class="btn bg-primary"
                                                @getphonenumber="phone"
                                                open-type="getPhoneNumber"
                                                data-type="1"
                                                :data-status="item.status"
                                                :data-index="index"
                                                :data-info="item.roomId"
                                            >
                                                预约
                                            </button>
                                        </block>
                                    </block>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="foot">
                        <view class="foot-top">
                            <view class="labels">
                                <view class="label disabled">不可用</view>
                                <view class="label">可预约</view>
                            </view>
                            <block v-if="item.status == 3">
                                <view class="tip color-attention" v-if="item.endTime">使用中 | {{ item.endTime }}结束</view>
                            </block>
                            <!-- <block wx:elif="{{item.status == 4 ||item.status == 2}}">
            <view class="tip color-attention" wx:if="{{item.endTime}}">
              已预订 | {{item.startTime}}开始
            </view>
          </block> -->
                        </view>
                        <view class="times">
                            <block v-for="(houritem2, index1) in timeHourAllArr[index]" :key="index1">
                                <view :class="'time ' + (houritem2.disable ? 'disabled' : '')">{{ houritem2.hour }}</view>
                            </block>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 温馨提示 -->
            <view class="notes">
                <view class="title border-primary">温馨提示</view>
                <view class="line">1.下单5分钟内可以取消订单或更换房间，超时将无法取消！</view>
                <view class="line">2.订单可以提前开始消费，提前开始提前结束。</view>
                <view class="line">3.消费时间不足时，我们进行提醒。若房间后续时间已被他人预定，将无法续费！请您留意消费时长！</view>
                <view class="line">4.预约时间结束后，房间将断电，灯光会自动熄灭。为了不影响下一位朋友使用，请您及时收拾物品离席。</view>
                <view class="line">5.严禁黄、赌、毒打架斗殴等一切违法活动！</view>
                <view class="line">6.破坏或带走本场所提供的设备设施请照价赔偿！</view>
                <view class="line">7.请自行保管好私人物品，如有遗失概不负责！</view>
                <view class="line">8.特殊情况，或需要帮助，请联系客服处理！</view>
            </view>
        </view>
    </view>
</template>
<script module="magic" lang="wxs" src="@/utils/magic.wxs"></script>
<script>
// pages/doorList/doorList.js
const app = getApp();
var http = require('../../utils/http.js');
var util1 = require('../../utils/util.js');
export default {
    data() {
        return {
            statusBarHeight: '',
            titleBarHeight: '',
            storeId: '',
            storeEnvImg: [],

            //图片数组
            bannerImg: [],

            //banner
            doorinfodata: {
                storeName: ''
            },

            //门店信息
            timeselectindex: 0,

            //日期选择索引值
            timebg_primary: 'bg-primary',

            timebg_primary_no: '',
            timeDayArr: [],

            //时间展示日期：年月日
            timeWeekArr: [],

            //时间展示：星期
            doorlistArr: [],

            //房间数组
            timeHourArr: [],

            //小时数组
            timeHourAllArr: [],

            //所有门店小时数组
            isLogin: app.globalData.isLogin,

            popshow: false,
            maoHeight: 0,

            //锚链接跳转高度
            tabIndex: 0,

            cautionText: `
              <p>
                <b>营业时间:</b>
                <span style="color: #b0b1b1;">24小时营业，可提前6天预约，3小时起约麻咖麻将馆(大象城店)，24小时营业，可提前6天预约，3小时起约</span>
              </p>
            `,

            labelitem: '',

            houritem2: {
                disable: false,
                hour: ''
            }
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {
        var that = this;
        that.getTap();
        that.loadingtime();
        if (options.storeId) {
            that.setData({
                storeId: options.storeId
            });
            console.info('options===');
            console.info(options.storeId);
            this.getDoorListdata();
            this.getDoorInfodata();
        }
        this.setData({
            statusBarHeight: uni.getStorageSync('statusBarHeight'),
            titleBarHeight: uni.getStorageSync('titleBarHeight'),
            popshow: true
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var that = this;
        that.setData({
            isLogin: app.globalData.isLogin
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        tabChange(e) {
            console.log(e);
            const { target } = e;
            this.setData(
                {
                    tabIndex: Number(target.dataset.index),
                    timeselectindex: 0
                },
                () => {
                    this.getDoorListdata();
                }
            );
        },

        popClose: function () {
            this.setData({
                popshow: false
            });
        },

        loadingtime: function () {
            var that = this;
            var date = new Date(); //获取当前时间
            var year = date.getFullYear(); //获取当前年份
            var month = date.getMonth() + 1; //获取当前月份
            var day = date.getDate(); //获取当前日期
            var atimestring = year + '-' + month + '-' + day;
            var atimestring1 = [year, month, day].map(util1.formatNumber).join('-');
            //console.log('atimestring1===11111');
            //console.log(atimestring1);

            var atimelist = that.getDates(5, atimestring1);
            var alist1 = [];
            var alist2 = [];
            for (var i = 0; i < atimelist.length; i++) {
                alist1.push(atimelist[i].month + '.' + atimelist[i].day);
                alist2.push(atimelist[i].week);
            }
            that.setData({
                timeDayArr: alist1,
                timeWeekArr: alist2
            });
        },

        //获取当前时间多少天后的日期和对应星期
        getDates: function (days, todate) {
            //todate默认参数是当前日期，可以传入对应时间
            var dateArry = [];
            for (var i = 0; i < days; i++) {
                var dateObj = this.dateLater(todate, i);
                dateArry.push(dateObj);
            }
            return dateArry;
        },

        /**
         * 传入时间后几天
         * param：传入时间：dates:"2019-04-12",later:往后多少天
         */
        dateLater: function (dates, later) {
            let dateObj = {};
            let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
            let date = new Date(dates);
            date.setDate(date.getDate() + later);
            let day = date.getDay();
            dateObj.year = date.getFullYear();
            dateObj.month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
            dateObj.day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
            dateObj.week = show_day[day];
            return dateObj;
        },

        getTap() {
            const SelectorQuery = uni.createSelectorQuery();
            SelectorQuery.select('#toolbar').boundingClientRect();
            SelectorQuery.exec((res) => {
                console.log(res[0]);
                if (res[0]) {
                    this.setData({
                        maoHeight: res[0].bottom + 200
                    });
                }
            });
        },

        goBack() {
            uni.navigateBack();
        },

        //获取门店相信信息
        getDoorInfodata: function (e) {
            var that = this;
            //if (app.globalData.isLogin)
            {
                http.request(
                    '/member/index/getStoreInfo/' + that.storeId,
                    '1',
                    'get',
                    {},
                    app.globalData.userDatatoken.accessToken,
                    '获取中...',
                    function success(info) {
                        console.info('门店信息===');
                        console.info(info);
                        if (info.code == 0) {
                            that.setData({
                                doorinfodata: info.data
                            });
                            if (null != info.data.storeEnvImg && info.data.storeEnvImg.length > 0) {
                                var arr = info.data.storeEnvImg.split(',');
                                that.setData({
                                    storeEnvImg: arr
                                });
                            }
                            if (null != info.data.bannerImg && info.data.bannerImg.length > 0) {
                                var arr = info.data.bannerImg.split(',');
                                that.setData({
                                    bannerImg: arr
                                });
                            }
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        //续费
        onclickxufei: function () {
            uni.showToast({
                title: '未找到订单',
                icon: 'none'
            });
        },

        tempArr: function (key) {
            Object.keys(aobject.disabledTimeSlot)
                .sort()
                .forEach(function (key) {
                    requestArr.push(key + '=' + aobject.disabledTimeSlot[key]);
                });
        },

        goOrder(e) {
            var that = this;
            if (that.isLogin) {
                //console.log('已经登录+++++++');
                let status = e.currentTarget.dataset.status;
                if (status == 0) {
                    return;
                }
                let aroomid = e.currentTarget.dataset.info;
                var atime = '';
                if (that.timeselectindex >= 0) {
                    atime = that.timeDayArr[that.timeselectindex];
                }
                var storeId = that.storeId;
                if (status == 2) {
                    if (that.doorinfodata.clearOpen) {
                        uni.showModal({
                            title: '提示',
                            content: '您选择的此场地暂未清洁，介意请勿预订！',
                            confirmText: '继续预定',
                            complete: (res) => {
                                if (res.confirm) {
                                    uni.navigateTo({
                                        url:
                                            '../orderSubmit/orderSubmit?roomId=' +
                                            aroomid +
                                            '&daytime=' +
                                            atime +
                                            '&storeId=' +
                                            storeId +
                                            '&timeselectindex=' +
                                            that.timeselectindex
                                    });
                                } else if (res.cancel) {
                                    //console.log('用户点击取消')
                                }
                            }
                        });
                    } else {
                        uni.showModal({
                            title: '提示',
                            content: '房间暂未清洁，禁止预订！',
                            showCancel: false
                        });
                    }
                } else {
                    uni.navigateTo({
                        url: '../orderSubmit/orderSubmit?roomId=' + aroomid + '&daytime=' + atime + '&storeId=' + storeId + '&timeselectindex=' + that.timeselectindex
                    });
                }
            }
        },

        phone: function (e) {
            var that = this;
            //console.log('手机号码授权+++++++');
            if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
                uni.showToast({
                    title: '已取消授权'
                });
            }
            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                //console.log('手机号码授权+++++++');
                uni.login({
                    success: function (res) {
                        if (res.code != null) {
                            http.request(
                                '/member/auth/weixin-mini-app-login',
                                '1',
                                'post',
                                {
                                    phoneCode: e.detail.code,
                                    loginCode: res.code
                                },
                                '',
                                '获取中...',
                                function success(info) {
                                    console.info('返回111===');
                                    console.info(info);
                                    if (info.code == 0) {
                                        if (info.data) {
                                            app.globalData.userDatatoken = info.data;
                                            app.globalData.isLogin = true;
                                            that.setData({
                                                isLogin: true
                                            });
                                            //缓存服务器返回的用户信息
                                            uni.setStorageSync('userDatatoken', info.data);
                                            that.goOrder(e);
                                        }
                                    }
                                },
                                function fail(info) {}
                            );
                        } else {
                            //console.log('登录失败！' + res.errMsg)
                        }
                    }
                });
            }
        },

        //获取房间列表数据
        getDoorListdata: function (e) {
            var that = this;
            //if (app.globalData.isLogin)
            {
                http.request(
                    '/member/index/getRoomInfoList/' + that.storeId + '?roomClass=' + that.tabIndex,
                    '1',
                    'post',
                    {
                        storeId: that.storeId,
                        roomClass: that.tabIndex
                    },
                    app.globalData.userDatatoken.accessToken,
                    '获取中...',
                    function success(info) {
                        console.info('返回111===');
                        console.info(info);
                        if (info.code == 0) {
                            that.setData({
                                doorlistArr: info.data
                            });
                            that.setroomlistHour(0);
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        //设置列表禁用时间轴
        setroomlistHour: function (aindex) {
            //aindex代表选的第几天  从0开始
            var that = this;
            console.log(aindex);
            var atemplist = [];
            //根据门店循环
            for (var i = 0; i < that.doorlistArr.length; i++) {
                var atemp = that.doorlistArr[i].timeSlot.slice(aindex * 24, aindex * 24 + 24);
                atemplist.push(atemp);
                // console.log(atemp);
            }

            console.log(atemplist);
            that.setData({
                timeHourAllArr: atemplist
            });
        },

        //选中时间
        selectTime: function (e) {
            let that = this;
            var index = e.currentTarget.dataset.index; //获取当前点击的下标
            that.setData({
                timeselectindex: index
            });
            that.setroomlistHour(index);
        },

        openDoor(e) {
            var that = this;
            // let aindex = e.currentTarget.dataset.index;
            if (that.isLogin) {
                uni.navigateTo({
                    url: '../orderDetail/orderDetail?toPage=true'
                });
            } else {
                that.gotologin();
            }
        },

        //到登录界面
        gotologin() {
            uni.navigateTo({
                url: '../login/login'
            });
        },

        //图片点击事件
        imgYu: function (event) {
            var that = this;
            let aindex = event.currentTarget.dataset.index;
            var alistimage = that.doorlistArr[aindex];
            var aimagearr = alistimage.imageUrls;

            //console.log("点击图片********")

            if (aimagearr.length > 0) {
                var anewimagearr = aimagearr.split(',');
                var src = anewimagearr[0] + '?Content-Type=image/jpg'; //获取data-src
                var imgList = anewimagearr; //获取data-list
                //图片预览
                uni.previewImage({
                    current: src,
                    // 当前显示图片的http链接
                    urls: imgList // 需要预览的图片http链接列表
                });
            } else {
                uni.showToast({
                    title: '该房间暂无图片介绍',
                    icon: 'none'
                });
            }
        }
    }
};
</script>
<style>
@import './booking.css';
</style>
